<template>
	<div class="node-box">
		<Input :input="input" :styles="styles" @change="change"/>
		<span class="send" @click="trySend" :class="{unClick: time}">{{time||'获取验证码'}}</span>
	</div>
</template>

<script>
export default{
	props:{
		input:{
			type: Object,
			default: () => ({
				name: 'node',
				placeholder: '请输入短信验证码'
			})
		},
		styles:{
			type: Object,
			default: () => ({
				cs: {
					paddingRight: '150px'
				},
				focus: {
					borderColor: '#00a1d6'
				}
			})
		},
		phone:{
			required: true
		}
	},
	data(){
		return{
			time: undefined
		}
	},
	methods:{
		// 尝试获取验证码
		trySend(){
			if(this.time) return;
			let {phone, reg} = this.phone,
					flag = reg.test(phone),
					errorType = ''
			if(phone == ''){
				errorType = 'nothing';
			}else if(!flag){
				errorType = 'format';
			}else{
				errorType = '';
				this.reckon();
			}
			this.$emit('error', errorType)
		},
		// 成功发送短信，并设置时差，父级调用，应该要保存一下，保存时间戳
		reckon(){
			this.time = 59;
			let timer = setInterval(()=>{
				this.time --;
				if(this.time==0) clearInterval(timer);
			},1000)
		},
		// node输入提交给父级
		change(name,val){
			this.$emit('change', name, val);
		}
	}
}
</script>

<style scoped lang="less">
.node-box{
	position: relative;
	.send{
		position: absolute;
		width: 130px;
		height: 36px;
		right: 2px;
		top: 2px;
		padding: 0 4px;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		font-size: 14px;
		color: #fff;
		background-color: #00a1d6;
		border-radius: 4px;
		cursor: pointer;
		&:hover{
			background-color: #33b4de;
		}
		&.unClick{
			cursor: not-allowed;
		}
	}
}
</style>
